<template>
  <el-dialog
    append-to-body
    :before-close="handleClose"
    title="任务分配"
    :visible.sync="dialogVisible"
  >
    <el-form
      ref="ruleForm"
      v-loading="loading"
      label-width="100px"
      :model="ruleForm"
      :rules="rules"
      size="mini"
    >
      <el-form-item label="人员" prop="user_id">
        <el-select v-model="ruleForm.user_id" filterable>
          <el-option
            v-for="(item, index) in users"
            :key="index"
            :label="`${item.last_name}${item.first_name} (${item.email})`"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit('ruleForm')">保存</el-button>
        <el-button @click="dialogVisible = false">返回</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import org from "@/api/org";
import threat from "@/api/threat";

export default {
  name: "Allocation",
  data() {
    return {
      dialogVisible: false,
      loading: false,
      ruleForm: {
        user_id: ""
      },
      rules: {
        user_id: [{ required: true, message: "请选择人员", trigger: "change" }]
      },
      org_id: "",
      threat_id: "",
      users: []
    };
  },
  watch: {
    dialogVisible: {
      handler: function(val) {
        if (!val) {
          this.ruleForm = {
            user_id: ""
          };
        }
      }
    }
  },
  methods: {
    handleClose(done) {
      done();
    },
    show(org_id, threat_id) {
      this.dialogVisible = !this.dialogVisible;
      this.org_id = org_id;
      this.threat_id = threat_id;
      this.loading = true;
      this.loadingUsers(org_id);
    },
    loadingUsers() {
      org
        .org_users({ org_id: this.org_id, limit: 20, page: 1 })
        .then(res => {
          this.users = res.data.users;
          this.loading = false;
        })
        .catch(() => {
          this.dialogVisible = false;
        });
    },
    submit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          threat
            .threat_assign({
              user_id: this.ruleForm.user_id,
              threat_id: this.threat_id
            })
            .then(res => {
              this.$message.success(res.data.message);
              this.dialogVisible = false;
              this.$emit("change");
            });
        } else {
          return false;
        }
      });
    }
  }
};
</script>
